#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "stockinfo.h"
#include "confighelper.h"
#include "configdialog.h"
#include "stockscontainer.h"

#include <QTableWidget>
#include <QTableWidgetItem>
#include <QDate>
#include <QMovie>

static QString STOCKGET_URI = "http://hq.sinajs.cn/list=sh000001,sz399001,%1";
static int WINDOW_WIDTH = 520;

MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent),
        ui(new Ui::MainWindowClass),
        nwaMgr_(0),
        timer_(0)
{
    createSystemTrayIcon();
    confHelper_ = new ConfigHelper("setting.ini");
    container_ = new StocksContainer();

    this->networkInit();
    this->uiInit();
    centerOnScreen();

    this->isProxyChanged = false;
    this->isStocksChanged = false;

    timer_ = new QTimer(this);
    connect(timer_, SIGNAL(timeout()), this, SLOT(slotStartNetWork()));
    timer_->start(confHelper_->getInterval());


    ui->labelWait->setGeometry(499, 5, 20, 20);
    QMovie* movie = new QMovie(":/images/wait.gif");
    ui->labelWait->setMovie(movie);

    movie->start();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete confHelper_;
    delete container_;
}

void MainWindow::slotStartNetWork()
{
    nwaMgr_->get(QNetworkRequest(QUrl(STOCKGET_URI.arg(confHelper_->getStocksStr()))));
}

void MainWindow::slotDownFinished(QNetworkReply *qnr)
{
    if (qnr->error() == QNetworkReply::NoError){

        QByteArray byteArray;
        for(int i=0; i<container_->size(); i++){
            byteArray = qnr->readLine(1000);
            container_->getStock(i)->refreshData(byteArray);
        }

    } else {
        timer_->stop();

        int ret = QMessageBox::warning(this, tr("网络失败"),
                                tr("网络连接失败，请检查网络!\n点击确定配置网络，取消退出程序"),
                                QMessageBox::Ok | QMessageBox::Cancel);

        if(ret == QMessageBox::Ok){
            emit this->ui->buttonConfig->click();
        }
        else
            qApp->exit(-1);
    }

    //需要删除qnr，不然会有内存泄漏
    qnr->deleteLater();

    if(ui->labelWait->isHidden() == false){
        ui->labelWait->setHidden(true);
    }
}

void MainWindow::slotIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::Trigger) {
        if(this->isHidden())
            this->showNormal();
        else
            this->hide();
    }

    if (reason == QSystemTrayIcon::DoubleClick) {
        this->showNormal();
    }
}

void MainWindow::slotConfigWindow()
{
    timer_->stop();
    //this->setHidden(false);

    ConfigDialog aa(this);

    if (aa.exec() == QDialog::Accepted){
        this->refreshWindow();
    }

    timer_->start(confHelper_->getInterval());
}

void MainWindow::uiInit()
{
    //init all stockInfo objects
    QStringList stockStrList = confHelper_->getStocksStr().split(',');

    Qt::WindowFlags flags = Qt::WindowTitleHint
                            | Qt::WindowMinimizeButtonHint
                            | Qt::WindowCloseButtonHint
                            | Qt::CustomizeWindowHint;

    if(confHelper_->getWindowStat() == 1){
        flags |= Qt::WindowStaysOnBottomHint;
    } else if(confHelper_->getWindowStat() == 2) {
        flags |= Qt::WindowStaysOnTopHint;
    }

    if(confHelper_->isNotOnToolbar())
        flags |= Qt::Tool;

    this->setWindowFlags(flags );
    ui->setupUi(this);

    QRect rectLabelTop(10, 5, WINDOW_WIDTH, 25);
    ui->labelTop->setGeometry(rectLabelTop);

    QRect rectTableTop(1, 30, WINDOW_WIDTH, 20);
    ui->tableWidgetTop->setGeometry(rectTableTop);
    QPalette p;
    p.setBrush(QPalette::Base,this->palette().window());
    ui->tableWidgetTop->setPalette(p);

    QRect rectLine(1, 50, WINDOW_WIDTH, 10);
    ui->line->setGeometry(rectLine);

    int linesOfStocksTable = stockStrList.size() + 1;

    QRect rectTable(1, 60, WINDOW_WIDTH, linesOfStocksTable*20);
    ui->tableWidget->setGeometry(rectTable);
    ui->tableWidget->setPalette(p);

    QRect rectLineBottom(1, 60+linesOfStocksTable*20, WINDOW_WIDTH, 10);
    ui->lineBottom->setGeometry(rectLineBottom);

    QRect rectButtonConfig(10, 60+linesOfStocksTable*20 +7, 30, 30);
    ui->buttonConfig->setGeometry(rectButtonConfig);
    ui->buttonConfig->setStyleSheet("QPushButton#buttonConfig:!hover{border-style:flat}");
    ui->buttonConfig->setToolTip(tr("配置"));
    connect(ui->buttonConfig, SIGNAL(clicked()), this, SLOT(slotConfigWindow()));

    QRect rectButtonExit(40, 60+linesOfStocksTable*20 +7, 30, 30);
    ui->buttonExit->setGeometry(rectButtonExit);
    ui->buttonExit->setStyleSheet("QPushButton#buttonExit:!hover{border-style:flat}");
    ui->buttonExit->setToolTip(tr("退出"));
    connect(ui->buttonExit, SIGNAL(clicked()), qApp, SLOT(quit()));

    int mainWindowHeight = 60+(linesOfStocksTable)*20+40;
    QRect rectMain(0, 0, WINDOW_WIDTH+2, mainWindowHeight);
    this->setGeometry(rectMain);

    QDate date = QDate::currentDate();
    ui->labelTop->setText(date.toString(tr("yyyy年MM月d日  dddd")));

    ui->tableWidget->setColumnWidth(0,90);
    ui->tableWidget->setColumnWidth(1,90);
    ui->tableWidget->setColumnWidth(2,70);
    ui->tableWidget->setColumnWidth(3,70);
    ui->tableWidget->setColumnWidth(4,70);
    ui->tableWidget->setColumnWidth(5,110);

    ui->tableWidget->setRowCount(linesOfStocksTable);

    ui->tableWidgetTop->setColumnWidth(0,60);
    ui->tableWidgetTop->setColumnWidth(1,75);
    ui->tableWidgetTop->setColumnWidth(2,60);
    ui->tableWidgetTop->setColumnWidth(3,40);
    ui->tableWidgetTop->setColumnWidth(4,20);
    ui->tableWidgetTop->setColumnWidth(5,60);
    ui->tableWidgetTop->setColumnWidth(6,85);
    ui->tableWidgetTop->setColumnWidth(7,60);
    ui->tableWidgetTop->setColumnWidth(8,40);
    ui->tableWidgetTop->setColumnWidth(9,20);

    this->setMaximumSize(WINDOW_WIDTH+2, mainWindowHeight);
    this->setMinimumSize(WINDOW_WIDTH+2, mainWindowHeight);

    stockStrList.push_front("sz399001");
    stockStrList.push_front("sh000001");
    for (int i = 0; i< stockStrList.size(); i++) {
        container_->addById(stockStrList[i]);
    }

    for(int i = 2; i < container_->size(); i++) {
        ui->tableWidget->setItem(i-1, 0, container_->getStock(i)->getTWIStockName());
        ui->tableWidget->setItem(i-1, 1, container_->getStock(i)->getTWIStockId());
        ui->tableWidget->setItem(i-1, 2, container_->getStock(i)->getTWIPercentage());
        ui->tableWidget->setItem(i-1, 3, container_->getStock(i)->getTWICurrentPrice());
        ui->tableWidget->setItem(i-1, 4, container_->getStock(i)->getTWIDiff());
        ui->tableWidget->setItem(i-1, 5, container_->getStock(i)->getTWIHighestLowest());
    }

    QTableWidgetItem *twi = new QTableWidgetItem();
    twi->setText(tr("亿"));
    twi->setTextAlignment(Qt::AlignLeft | Qt::AlignTop);

    ui->tableWidgetTop->setItem(0,0, container_->getStock(0)->getTWIStockName());
    ui->tableWidgetTop->setItem(0,1, container_->getStock(0)->getTWICurrentPrice());
    ui->tableWidgetTop->setItem(0,2, container_->getStock(0)->getTWIPercentage());
    ui->tableWidgetTop->setItem(0,3, container_->getStock(0)->getTWIVolume());
    ui->tableWidgetTop->setItem(0,4, twi);


    QTableWidgetItem *twi2 = new QTableWidgetItem();
    twi2->setText(tr("亿"));
    twi2->setTextAlignment(Qt::AlignLeft | Qt::AlignTop);
    ui->tableWidgetTop->setItem(0,5, container_->getStock(1)->getTWIStockName());
    ui->tableWidgetTop->setItem(0,6, container_->getStock(1)->getTWICurrentPrice());
    ui->tableWidgetTop->setItem(0,7, container_->getStock(1)->getTWIPercentage());
    ui->tableWidgetTop->setItem(0,8, container_->getStock(1)->getTWIVolume());
    ui->tableWidgetTop->setItem(0,9, twi2);


    QTableWidgetItem *it = new QTableWidgetItem(tr("名称"));
    it->setTextAlignment(Qt::AlignHCenter);
    ui->tableWidget->setItem(0,0,it);

    QTableWidgetItem *it1 = new QTableWidgetItem(tr("代码"));
    it1->setTextAlignment(Qt::AlignHCenter);
    ui->tableWidget->setItem(0,1,it1);

    QTableWidgetItem *it2 = new QTableWidgetItem(tr("涨跌幅"));
    it2->setTextAlignment(Qt::AlignRight);
    ui->tableWidget->setItem(0,2,it2);

    QTableWidgetItem *it3 = new QTableWidgetItem(tr("最新价"));
    it3->setTextAlignment(Qt::AlignRight);
    ui->tableWidget->setItem(0,3,it3);

    QTableWidgetItem *it4 = new QTableWidgetItem(tr("涨跌额"));
    it4->setTextAlignment(Qt::AlignRight);
    ui->tableWidget->setItem(0,4,it4);

    QTableWidgetItem *it5 = new QTableWidgetItem(tr(" 最高/最低"));
    it5->setTextAlignment(Qt::AlignHCenter);
    ui->tableWidget->setItem(0,5,it5);

}

void MainWindow::networkInit()
{
    if(nwaMgr_ == 0) {
        nwaMgr_ = new QNetworkAccessManager(this);
        connect(nwaMgr_, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(slotDownFinished(QNetworkReply*)));
    }

    QNetworkProxy proxy;
    if (confHelper_->isProxyEnable()){
        proxy.setType(QNetworkProxy::HttpProxy);
        proxy.setHostName(confHelper_->getProxy());
        proxy.setPort(confHelper_->getProxyPort());
        nwaMgr_->setProxy(proxy);
    } else {
        proxy.setType(QNetworkProxy::NoProxy);
        nwaMgr_->setProxy(proxy);
    }
}

void MainWindow::refreshTableContent()
{

    //重新刷新表格里面的内容,先移除旧的内容
    for(int i = 1; i < ui->tableWidget->rowCount(); i++) {
        for(int j=0; j< ui->tableWidget->columnCount(); j++)
            ui->tableWidget->takeItem(i,j);
    }

    // 需要更新，股票表格，按钮，主窗口的大小
    QStringList stockStrList = this->confHelper_->getStocksStr().split(',');

    QPalette p;
    p.setBrush(QPalette::Base,this->palette().window());

    //添加多一行，因为里面包含了上证和深成
    int linesOfStocksTable = stockStrList.size() + 1;

    QRect rectTable(1, 60, 520, linesOfStocksTable*20);
    ui->tableWidget->setGeometry(rectTable);
    ui->tableWidget->setPalette(p);

    QRect rectLineBottom(1, 60+linesOfStocksTable*20, 520, 10);
    ui->lineBottom->setGeometry(rectLineBottom);

    QRect rectButtonConfig(10, 60+linesOfStocksTable*20 +7, 30, 30);
    ui->buttonConfig->setGeometry(rectButtonConfig);

    QRect rectButtonExit(40, 60+linesOfStocksTable*20 +7, 30, 30);
    ui->buttonExit->setGeometry(rectButtonExit);

    int mainWindowHeight = 60+(linesOfStocksTable)*20+40;
    QRect rectMain(this->geometry().x(), this->geometry().y(), 502, mainWindowHeight);
    this->setGeometry(rectMain);

    ui->tableWidget->setRowCount(linesOfStocksTable);

    this->setMaximumSize(522, mainWindowHeight);
    this->setMinimumSize(522, mainWindowHeight);

    container_->readdByIds(stockStrList, *this->confHelper_);

    for(int i = 2; i < container_->size(); i++) {
        ui->tableWidget->setItem(i-1, 0, container_->getStock(i)->getTWIStockName());
        ui->tableWidget->setItem(i-1, 1, container_->getStock(i)->getTWIStockId());
        ui->tableWidget->setItem(i-1, 2, container_->getStock(i)->getTWIPercentage());
        ui->tableWidget->setItem(i-1, 3, container_->getStock(i)->getTWICurrentPrice());
        ui->tableWidget->setItem(i-1, 4, container_->getStock(i)->getTWIDiff());
        ui->tableWidget->setItem(i-1, 5, container_->getStock(i)->getTWIHighestLowest());
    }

}

void MainWindow::closeEvent(QCloseEvent *event)
{
    this->hide();
    event->ignore();
}

void MainWindow::centerOnScreen ()
{
    int x = QApplication::desktop()->availableGeometry().width();
    int y = QApplication::desktop()->availableGeometry().height();
    this->move((x-this->width())/2, (y-this->height())/2);
}

void MainWindow::refreshWindow()
{
    if(isStocksChanged) {
        this->refreshTableContent();
        isStocksChanged = false;

        if(this->confHelper_->getHasnew() == true)
            this->ui->labelWait->setHidden(false);
    }

    if(isProxyChanged){
        this->networkInit();
        isProxyChanged = false;
        this->ui->labelWait->setHidden(false);
    }

    Qt::WindowFlags flags = this->windowFlags();
    flags = 0;
    if(confHelper_->getWindowStat() == 1){
        this->setWindowFlags(flags);
        flags |= Qt::WindowStaysOnBottomHint;
    } else if(confHelper_->getWindowStat() == 2) {
        this->setWindowFlags(flags);
        flags |= Qt::WindowStaysOnTopHint;
    }

    if(confHelper_->isNotOnToolbar())
        flags |= Qt::Tool;

    this->setWindowFlags(flags);


    QPoint pos = this->pos();
         if (pos.x() < 0)
             pos.setX(0);
         if (pos.y() < 0)
             pos.setY(0);
    this->move(pos);

    this->show();
}

void MainWindow::createSystemTrayIcon()
{
    settingAction = new QAction(tr("设置(&S)"), this);
    QIcon settingIcon(":/images/configure.png");
    settingAction->setIcon(settingIcon);
    connect(settingAction, SIGNAL(triggered()), this, SLOT(slotConfigWindow()));

    minimizeAction = new QAction(tr("隐藏(&M)"), this);
    connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));

    restoreAction = new QAction(tr("恢复(&R)"), this);
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));

    quitAction = new QAction(tr("退出(&Q)"), this);
    QIcon quitIcon(":/images/exit.png");
    quitAction->setIcon(quitIcon);
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

    trayIconMenu_ = new QMenu(this);
    trayIconMenu_->addAction(minimizeAction);
    trayIconMenu_->addAction(settingAction);
    trayIconMenu_->addAction(restoreAction);
    trayIconMenu_->addSeparator();
    trayIconMenu_->addAction(quitAction);

    trayIcon_ = new QSystemTrayIcon(this);
    QIcon qi(":/images/app.png");
    trayIcon_->setToolTip(tr("股票监控小助手"));
    trayIcon_->setIcon(qi);
    trayIcon_->setContextMenu(trayIconMenu_);
    trayIcon_->show();

    connect(trayIcon_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(slotIconActivated(QSystemTrayIcon::ActivationReason)));
}
